package cn.cdeden.resource.controller;

import cn.cdeden.common.core.domain.R;
import cn.cdeden.common.core.exception.ServiceException;
import cn.cdeden.common.oss.enumd.OssModuleType;
import cn.cdeden.common.satoken.utils.LoginHelper;
import cn.cdeden.resource.domain.SysOssEs;
import cn.cdeden.resource.service.OssFileEsService;
import cn.cdeden.system.api.model.LoginUser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.easyes.core.conditions.select.LambdaEsQueryWrapper;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;


/**
 * es 测试 查询处理器
 * @ProjectName : KnowCore
 * @Package : cn.cdeden.resource.es.controller
 * @ClassName : SysOssEsCrudController
 * @Author : Yu.
 * @Description : // TODO
 * @Date : 2024/12/10 9:26
 * @Version : 1.0
 */
@Slf4j
@RestController
@RequestMapping("/es/oss")
@RequiredArgsConstructor
@ConditionalOnProperty(value = "easy-es.enable", havingValue = "true")
public class SysOssEsCrudController {


    private final OssFileEsService ossEsService;


    /**
     * 搜索(模糊)
     *
     * @param key 搜索关键字
     */
    @GetMapping("/search")
    public List<SysOssEs> search(String key) {
        LambdaEsQueryWrapper<SysOssEs> wrapper = new LambdaEsQueryWrapper<>();
        wrapper.like(SysOssEs::getTitle, key)
            .or().
            like(SysOssEs::getContent, key)
        ;
        wrapper.orderByDesc(SysOssEs::getCreateTime);
        return ossEsService.selectList(wrapper);
    }

    /**
     * 搜索信息(模糊)
     *
     * @param info 搜索关键字
     */
    @GetMapping("/searchInfo")
    public List<SysOssEs> searchInfo(SysOssEs info) {
        String moduleType = info.getModuleType();
        OssModuleType coedInfo = OssModuleType.findCoedInfo(moduleType);
//        if (coedInfo == null){
//            throw new IllegalStateException("意外的值: " + moduleType);
//        }else{
        LoginUser loginUser = LoginHelper.getLoginUser();//获取用户信息
        info.setUserIdList(Arrays.asList(String.valueOf(loginUser.getUserId())));
        switch (coedInfo){
//            case Temporary:
            case Personal:
                break;
            case Enterprise:
//                info.setPostIdList(loginUser.getPostIdList()); //获取用户岗位
                info.setDeptIdList(loginUser.getDeptIds()); //获取用户部门
                info.setRoleIdList(loginUser.getRolesIds()); //获取用户角色
                break;
            default: throw new ServiceException("意外的值的,没有文件类容搜索");
        }
        return ossEsService.selectList(info);
    }


//
//    /**
//     * 插入
//     */
//    @PostMapping("/add")
//    public Integer insert(@RequestBody SysOssEs document) throws IOException {
//        Path path = Paths.get("D:\\software\\sys\\Desktop\\01.txt");
//        byte[] fileBytes = Files.readAllBytes(path);
//        String base64 = Base64.getEncoder().encodeToString(fileBytes);
//        document.setContent(base64);
//        return ossEsService.insert(document);
//    }





//    public void uploadToEasyEs(String content) {
//        // 初始化EsClient
//
//        // 创建索引（如果索引不存在）
//        CreateIndexRequest createIndexRequest = new CreateIndexRequest("files");
//        CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest);
//        if (createIndexResponse.isAcknowledged()) {
//            System.out.println("Index created successfully.");
//        }
//
//        // 构建文档
//
//        // 上传文档到索引
//        IndexRequest indexRequest = new IndexRequest("files").id("1").source(document);
//        IndexResponse indexResponse = esClient.index(indexRequest);
//        if (indexResponse.getResult() == DocWriteResponse.Result.CREATED || indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
//            System.out.println("Document uploaded successfully.");
//        }
//    }



    /**
     * 更新
     */
    @PostMapping("/update")
    public R update(@RequestBody SysOssEs document) {
        // 测试更新 更新有两种情况 分别演示如下:
        // case1: 已知id, 根据id更新 (为了演示方便,此id是从上一步查询中复制过来的,实际业务可以自行查询)
        ossEsService.updateById(document);

        // case2: id未知, 根据条件更新
//        LambdaEsUpdateWrapper<Document> wrapper = new LambdaEsUpdateWrapper<>();
//        wrapper.like(Document::getTitle, document.getTitle());
//        Document document2 = new Document();
//        document2.setTitle(document.getTitle());
//        document2.setContent(document.getContent());
//        documentMapper.update(document2, wrapper);

        return R.ok();
    }

    /**
     * 删除
     *
     * @param id 主键
     */
    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable String id) {
        // 测试删除数据 删除有两种情况:根据id删或根据条件删
        boolean b = ossEsService.deleteById(id);
        return R.ok();
    }




}
